#include "func.h"
#include "threadPool.h"
#include "msgHandler.h"

#include "login.h"

#define RET_SUCCESS "success"
#define RET_FAIL "fail"

void extractSubstring(const char* str, char* substring, size_t substringSize) {
    const char* startDelimiter = strchr(str, '$');
    const char* endDelimiter = strrchr(str, '$');

    if (startDelimiter && endDelimiter && startDelimiter != endDelimiter) {
        size_t substringLength = endDelimiter - startDelimiter + 1;
        if (substringLength < substringSize) {
            strncpy(substring, startDelimiter, substringLength);
            substring[substringLength] = '\0';
        } else {
            strncpy(substring, startDelimiter, substringSize - 1);
            substring[substringSize - 1] = '\0';
        }
    }
}


/* int login(const char *username,char *passwd,int netfd) */
int login(const int netfd, const user_t *pusr) {
    printf("netfd = %d, username = %s, passwd = %s\n", netfd, pusr->name, pusr->passwd);
    char *user;
    char salt[512]={0};
    int i,j;

    train_t train;

    char buf[4096] = {0};
    memcpy(buf,pusr->passwd,strlen(pusr->passwd));
    struct spwd *sp = getspnam(pusr->name);

    if(sp==NULL)
    {
        bzero(&train,sizeof(train));
        printf("The user does not exist! Please re-enter!\n");
        memcpy(train.data, RET_FAIL, strlen(RET_FAIL));
        train.length=strlen(train.data);
        send_msg(netfd, &train);
        return -1;
    }

    extractSubstring(sp->sp_pwdp, salt, sizeof(salt));
    strncpy(salt,sp->sp_pwdp,i);

    bzero(&train,sizeof(train));
    
    if(strcmp(sp->sp_pwdp,crypt(buf,salt))==0)
    {
        printf("验证通过！\n");
        memcpy(train.data, RET_SUCCESS, strlen(RET_SUCCESS));
        train.length=strlen(train.data);
        send_msg(netfd, &train);
        return 0;
    }
    else
    {
        printf("密码错误！\n");
        memcpy(train.data, RET_FAIL, strlen(RET_FAIL));
        train.length=strlen(train.data);
        send_msg(netfd, &train);
        return -1;
    }
}
